<template>
  <div>
    <el-form
      :model="form"
      label-position="left"
      label-width="100px"
      :rules="rules"
      ref="loginForm"
    >
      <el-form-item
        class="email-input"
        prop="usernameOrEmail"
        label="邮箱/用户名"
      >
        <el-input
          v-model="form.usernameOrEmail"
          placeholder="请输入用户名或邮箱"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码" class="password-input">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          clearable
        ></el-input>
      </el-form-item>
      <div class="footer">
        <el-checkbox v-model="form.remember" style="margin-top: 10px"
          ><span style="color: #333; margin-top: 5px">记住我</span></el-checkbox
        >
        <el-button type="primary" @click="submit">登录</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import request from "@/utils/request";
export default {
  data() {
    return {
      form: {
        usernameOrEmail: "",
        password: "",
        remember: false,
      },
      rules: {
        usernameOrEmail: [
          { required: true, message: "请输入账号或邮箱", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    submit() {
      // 表单验证
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          const payload = {
            password: this.form.password,
          };

          if (this.isEmail(this.form.usernameOrEmail)) {
            payload.email = this.form.usernameOrEmail;
          } else {
            payload.username = this.form.usernameOrEmail;
          }

          // 在这里可以进行实际的登录操作，比如调用 API
          await this.handleLogin(payload);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    isEmail(value) {
      const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
      return emailPattern.test(value);
    },
    async handleLogin(payload) {
      try {
        const res = await request({
          url: "/api/users/tokens",
          method: "POST",
          data: payload,
        });
        // 登录成功后，可以调用 this.$router.push 跳转到相应页面
        this.handleLoginSuccess(res);
      } catch (err) {
        console.error(err);
        this.$message.error(err.response.data.message);
        return false;
      }
    },
    handleLoginSuccess(res) {
      // 登录成功后，将 token 存储到 localStorage 中
      // 并根据 token 信息判断是否为管理员，如果不是管理员，则提示错误信息并返回
      if (res.data.role !== "admin") {
        this.$message.error("你不是管理员，请联系管理员");
        return false;
      }
      //如果记住我被勾选，就储存账号
      if (this.form.remember) {
        localStorage.setItem("usernameOrEmail", this.form.usernameOrEmail);
      }

      localStorage.setItem("token", res.data.auth);
      this.$message.success("登录成功");
      this.$router.push({ name: "home" });
    },
  },
  async mounted() {
    // 如果本地有账号信息，则自动填充到表单中
    const usernameOrEmail = localStorage.getItem("usernameOrEmail");
    if (usernameOrEmail) {
      this.form.usernameOrEmail = usernameOrEmail;
      this.form.remember = true;
    }
  },
};
</script>

<style scoped lang="scss">
.el-form {
  padding: 0 3em;
}
.email-input,
.password-input {
  margin-top: 2.5rem;
  color: #000;
}

.footer {
  display: flex;
  justify-content: space-between;
}
</style>
